package com.bruce.springbootDemo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @param
 * @author bruce
 * @date 18/11/22 15:11
 * @Description: 描述--用户相关的信息拦截
 * @return
 */
@Configuration
public class LogInterceptors implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 进controller前调用此方法
     *
     * @param request  请求
     * @param response 相应
     * @param handler  参数
     * @return true 就通过拦截器，false就拦截不让通过
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("请求开始：" + request.getSession().getId());
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                String beanName = handlerMethod.getBean().getClass().toString();//类
                String methodName = handlerMethod.getMethod().getName();//方法名称
                String uri = request.getRequestURI();//请求路径
                String remoteAddr = getIpAddr(request);//ip
                String method = request.getMethod(); //请求方式
                Map<String, String[]> pramMap = request.getParameterMap();
                StringBuffer sbf = new StringBuffer();
                int count = 0;
                String forCunt = "";
                for (Map.Entry<String, String[]> entry : pramMap.entrySet()) {
                    forCunt = "[" + count + "]" + " : ";
                    sbf.append("paramName" + forCunt + entry.getKey() + " - " + "paramValue" +
                            forCunt + request.getParameter(entry.getKey()) + "\n");
                    count++;
                }
                logger.info("beanName : " + beanName);
                logger.info("方法名 : " + methodName);
                logger.info("请求url : " + uri + " | " + "IP地址 : " + remoteAddr + " | " + "请求方法 : " + method);
                logger.info("参数列表 : " + sbf);
            }
        } catch (Exception e) {
            //出错
            logger.error("用户操作日志记录异常", "RequestParamInfoIntorceptor");
        }
        return true;
    }

    /**
     * controller处理完了,渲染页面前，就会调用此方法
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    /**
     * 页面渲染完了调用此方法,类似finally,用来清理某些资源
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.info("请求结束：" + request.getSession().getId());
    }

    //获取客户端IP
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
